package com.goexchange.controller;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.*;

import com.goexchange.data.Email;
import com.goexchange.data.PMF;
import com.goexchange.data.Subscriber;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class Register extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		doPost(req, resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String email = req.getParameter("email");
		
		Subscriber subscriber = new Subscriber(email, new Date());
		Key key = KeyFactory.createKey(Subscriber.class.getSimpleName(), email);
		subscriber.setKey(key);
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.makePersistent(subscriber);
			sendEmail(email);
		}finally{
			pm.close();
		}
	}
	
	private void sendEmail(String email){
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		try{
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(Email.AdminEMAIL));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
			msg.setSubject(Email.SUBJECT);
			msg.setText(Email.CONTENT);
			Transport.send(msg);
		}catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}
